package com.nari.ncps.screen.service.impl.al;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlProdoperStock;
import com.nari.ncps.screen.entity.coal.CoalOpermonRtEffect;
import com.nari.ncps.screen.mapper.al.AlProdoperStockMapper;
import com.nari.ncps.screen.service.al.AlProdoperStockService;
import com.nari.ncps.screen.vo.al.AlProdoperStockVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 铝合金产品库存情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class AlProdoperStockServiceImpl extends ServiceImpl<AlProdoperStockMapper, AlProdoperStock> implements AlProdoperStockService {

    @Override
    public List<AlProdoperStockVO> getAlloyStockData() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        LocalDate startDate = currentDate.minusMonths(11);

        // 获取当前年月
        String currentYearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 获取去年同期年月（减去1年）
//        String lastYearSameMonth = LocalDate.now().minusYears(1).format(DateTimeFormatter.ofPattern("yyyyMM"));
        String lastYearSameMonth = startDate.format(DateTimeFormatter.ofPattern("yyyyMM"));

//        // 先从数据库查询最近12个月的数据
//        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<AlProdoperStock> queryWrapper =
//            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
//        queryWrapper.ge("year", startDate.getYear())
//                   .orderByAsc("year", "month");

        // 近12个月的日期
        LocalDate months = currentDate.minusMonths(11);

        // 查询最近12个月的数据
        LambdaQueryWrapper<AlProdoperStock> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(AlProdoperStock::getYear, months.getYear())
                .eq(AlProdoperStock::getDateType, 1)
                .eq(AlProdoperStock::getOrgCode, 100360)
                .between(AlProdoperStock::getStatisticTime, lastYearSameMonth,currentYearMonth)
                .orderByDesc(AlProdoperStock::getYear)
                .orderByDesc(AlProdoperStock::getMonth);
        
        List<AlProdoperStock> stockList = this.list(wrapper);
        
        // 如果数据库中没有数据，返回mock数据
        if (stockList == null || stockList.isEmpty()) {
            return generateMockAlloyStockData(currentDate);
        }
        
        // 转换为VO对象
        List<AlProdoperStockVO> voList = new ArrayList<>();
        for (AlProdoperStock entity : stockList) {
            AlProdoperStockVO vo = new AlProdoperStockVO();
            vo.setYear(entity.getYear());
            vo.setMonth(entity.getMonth());
            vo.setAluminumStock(entity.getAluminumStock());
            voList.add(vo);
        }
        
        return voList;
    }
    
    /**
     * 生成mock铝合金产品库存数据（最近12个月）
     * 覆盖全场景：包括生产周期影响、销售旺季淡季、库存管理策略等
     */
    private List<AlProdoperStockVO> generateMockAlloyStockData(LocalDate currentDate) {
        List<AlProdoperStockVO> mockData = new ArrayList<>();
        
        // 基础库存量：50000吨
        BigDecimal baseStock = new BigDecimal("50000");
        
        // 生成最近12个月的数据
        for (int i = 11; i >= 0; i--) {
            LocalDate monthDate = currentDate.minusMonths(i);
            AlProdoperStockVO vo = new AlProdoperStockVO();
            vo.setYear(monthDate.getYear());
            vo.setMonth(monthDate.getMonthValue());
            
            // 模拟不同场景的库存变化：
            // 1-2月：春节前后，库存积累，较高
            // 3-5月：春季销售旺季，库存下降
            // 6-8月：夏季生产高峰，库存回升
            // 9-10月：秋季销售旺季，库存下降
            // 11-12月：年底备货，库存上升
            int month = monthDate.getMonthValue();
            double seasonalFactor = 0.0;
            
            if (month >= 1 && month <= 2) {
                // 春节期间：库存积累（+15% ~ +25%）
                seasonalFactor = 0.15 + (Math.random() * 0.10);
            } else if (month >= 3 && month <= 5) {
                // 春季销售旺季：库存下降（-10% ~ 0%）
                seasonalFactor = -0.10 + (Math.random() * 0.10);
            } else if (month >= 6 && month <= 8) {
                // 夏季生产高峰：库存回升（+5% ~ +15%）
                seasonalFactor = 0.05 + (Math.random() * 0.10);
            } else if (month >= 9 && month <= 10) {
                // 秋季销售旺季：库存下降（-5% ~ +5%）
                seasonalFactor = -0.05 + (Math.random() * 0.10);
            } else {
                // 年底备货：库存上升（+10% ~ +20%）
                seasonalFactor = 0.10 + (Math.random() * 0.10);
            }
            
            // 添加随机波动（±2000吨）
            double randomVariation = -2000 + (Math.random() * 4000);
            
            // 计算最终库存
            BigDecimal seasonalAdjustment = baseStock.multiply(new BigDecimal(seasonalFactor));
            BigDecimal stock = baseStock.add(seasonalAdjustment).add(new BigDecimal(randomVariation));
            
            // 确保库存不低于30000吨，不高于80000吨
            if (stock.compareTo(new BigDecimal("30000")) < 0) {
                stock = new BigDecimal("30000");
            } else if (stock.compareTo(new BigDecimal("80000")) > 0) {
                stock = new BigDecimal("80000");
            }
            
            vo.setAluminumStock(stock.setScale(2, RoundingMode.HALF_UP));
            mockData.add(vo);
        }
        
        return mockData;
    }
}
